import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入获取TOKEN功能
import { getItem } from '../utils/auth'

//导入nprogress加载进度条
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// 全局注册频道模块
import HmSelect from '@/components/hmSelect.vue'
Vue.component('HmSelect', HmSelect)

// 组件导入
const Login = () => import('@/views/login')
const Home = () => import('@/views/home')
const Article = () => import('@/views/article')
const Publish = () => import('@/views/publish')
const Layout = () => import('@/views/layout')

// 注册路由
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },

  {
    path: '/',
    component: Layout,
    // redirect重定向
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/article',
        component: Article
      },
      {
        path: '/publish',
        component: Publish
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

//前置守卫
router.beforeEach((to, from, next) => {
  Nprogress.start()
  if (getItem()) {
    if (to.path.toLowerCase() === '/login') {
      next('/home')
    } else {
      next()
    }
  } else {
    if (to.path.toLowerCase() === '/login') {
      next()
    } else {
      next('/login')
    }
  }
  Nprogress.done()
})

// 后置守卫
router.afterEach((to, from) => {
  Nprogress.done()
})
export default router
